package team.pra.manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.pra.manager.common.utils.TokenGenerator;
import team.pra.manager.mapper.SysTokenMapper;
import team.pra.manager.mapper.UserMapper;
import team.pra.manager.pojo.SysToken;
import team.pra.manager.pojo.User;
import team.pra.manager.service.ShiroService;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired(required = false)
    private SysTokenMapper sysTokenMapper;
    @Autowired(required = false)
    private UserMapper userMapper;

    private final static int EXPIRE = 12;

    @Override
    public User findByUsername(String username) {
        User user = userMapper.findUserByUserName(username);
        return user;
    }

    @Override
    public Map<String, Object> createToken(Integer userId) {
        Map<String, Object> result = new HashMap<>();
        //生成一个token
        String token = TokenGenerator.generateValue();
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        //过期时间
        LocalDateTime expireTime = now.plusHours(EXPIRE);
        //判断是否生成过token
        SysToken tokenEntity = sysTokenMapper.selectByUserId(userId);
        if (tokenEntity == null) {
            tokenEntity = new SysToken();
            tokenEntity.setUserId(userId);
            //保存token
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            sysTokenMapper.insertToken(tokenEntity);
        } else {
            //更新token
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            sysTokenMapper.updateToken(tokenEntity);
        }
        result.put("token", token);
        result.put("expire", expireTime);
        return result;
    }

    @Override
    public void logout(String token) {
        SysToken tokenEntity = findByToken(token);
        token = TokenGenerator.generateValue();
        //修改token
        tokenEntity.setToken(token);
        //更新数据库Token，使前端获取到的token失效
        sysTokenMapper.updateToken(tokenEntity);
    }

    @Override
    public SysToken findByToken(String accessToken) {
        return sysTokenMapper.selectByToken(accessToken);
    }

    @Override
    public User findByUserId(Integer userId) {
        return userMapper.findUserById(userId);
    }
}
